//
//  Pusher.swift
//  CapPush
//
//  Created by 李加建 on 2021/9/26.
//

public enum Pusher {
    public static var registrationID: String?
    static var mediator = PusherMediator()
    static func registerRemoteNotification() {
        UIApplication.shared.registerForRemoteNotifications()
        let entity = JPUSHRegisterEntity()
        entity.types = NSInteger(JPAuthorizationOptions.alert.rawValue) |
            NSInteger(JPAuthorizationOptions.sound.rawValue) |
            NSInteger(JPAuthorizationOptions.badge.rawValue)
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: mediator)

        JPUSHService.setLogOFF()
    }

    public static func addDelegate(_ delegate: PusherDelegate?) {
        mediator.delegate = delegate
    }

    public static func setup(withOption option: [AnyHashable: Any]?, appKey: String, channel: String, apsForProduction: Bool) {
        registerRemoteNotification()
        JPUSHService.setup(withOption: option, appKey: appKey, channel: channel, apsForProduction: apsForProduction)
    }

    public static func getRegistrationID(complete: @escaping (String?) -> Void) {
        // JPush登录
        JPUSHService.registrationIDCompletionHandler { _, registrationID in
            self.registrationID = registrationID
            complete(registrationID)
        }
    }

    public static func registerDeviceToken(deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }

    public static func didReceiveRemoteNotification(userInfo: [AnyHashable: Any]?) {
        JPUSHService.handleRemoteNotification(userInfo)
    }
}

public extension Pusher {
    static func showDeviceToken(_ deviceToken: Data) -> String {
        deviceToken.map {
            String(format: "%02.2hhx", arguments: [$0])
        }.joined()
    }
}

class PusherMediator: NSObject {
    weak var delegate: PusherDelegate?
}

extension PusherMediator: JPUSHRegisterDelegate {
    func jpushNotificationCenter(_: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        let isPush = notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) ?? false
        if isPush {
            let userInfo = notification.request.content.userInfo
            print("jpush ==== \(userInfo)")
            delegate?.handleRemoteNotification(userInfo, isClick: false)
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler(Int(UNNotificationPresentationOptions.badge.rawValue | UNNotificationPresentationOptions.sound.rawValue | UNNotificationPresentationOptions.alert.rawValue))
    }

    func jpushNotificationCenter(_: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        let isPush = response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) ?? false
        if isPush {
            let userInfo = response.notification.request.content.userInfo
            print("jpush ==== \(userInfo)")
            delegate?.handleRemoteNotification(userInfo, isClick: true)
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler()
    }

    func jpushNotificationCenter(_: UNUserNotificationCenter!, openSettingsFor notification: UNNotification!) {
        let isPush = notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) ?? false
        if isPush {
            // 从通知界面直接进入应用
        } else {
            // 从通知设置界面进入应用
        }
    }

    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable: Any]!) {
        print("jpush ==== \(info) \(status.rawValue)")
    }
}

extension Pusher {
    //
}

public protocol PusherDelegate: AnyObject {
    func handleRemoteNotification(_ userInfo: [AnyHashable: Any], isClick: Bool)
}
